<?php

namespace App\Http\Resources;
use App\Models\Record;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Support\Str;

class StrangerResource extends JsonResource
{

    public function toArray($request)
    {
        $stranger = $this->stranger;
        $user = $this->user;
        $result = Record::where([
            ['from_id', '=', $stranger->id],
            ['to_id', '=', $user->id],
        ])->orwhere([
            ['from_id', '=', $user->id],
            ['to_id', '=',  $stranger->id],
        ])->latest()->first();
        $excerpt = '';
        if($result){
            switch ($result->type){
                case "image": $excerpt = "[图片]";
                    break;
                case "video": $excerpt = "[视频]";
                    break;
                case "audio": $excerpt = "[音频]";
                    break;
                case "speech": $excerpt = "[语音]";
                    break;
                case "videocall": $excerpt = "[视频通话]";
                    break;
                case "voicecall": $excerpt = "[语音通话]";
                    break;
                default:  $excerpt = Str::limit( $result->content, 100);
            }
        }
        return [
            'stranger' =>   new UserResource($stranger),
            /*'record' =>new RecordResource(
                Record::where("to_id",$this->user_id)
                    ->where("from_id",$this->stranger_id)
                    ->latest()
                    ->first()
            ),*/
            "count" =>Record::where(
                "to_id",$user->id
            )->where(
                "from_id",$stranger->id
            )->where(
                "read",0
            )->count(),
            "type" => $this->type,
            'id' => $stranger->id,
            'online' => $stranger->online,
            "excerpt" => $excerpt,
            'created_at' => (string) $this->created_at->format('Y-m-d H:i:s'),
            'updated_at' => (string) $this->updated_at->format('Y-m-d H:i:s'),
        ];
    }
}
